define(['drawingManager', 'lushu', 'Datetimepicker'], function (drawingManager, lushu, datetimepicker) {
    return {
        init: function () {
            datetimepicker.Datetimepicker($('input.timepicker'), {
                format: "yyyy-mm-dd hh:ii",
                todayBtn: true,
                minView: 0,
            });
            $("#pause").attr('disabled', true);

            $("#search").on('click',function () {
                load();

            })
            var eTime=$("#time").val();
            var sTime=(parseInt($("#time").val()) -100)+"";
            $('#timeEtart').val(eTime.substr(0,4)+"-"+eTime.substr(4,2)+"-"+eTime.substr(6,2)+" "+eTime.substr(8,2)+":"+eTime.substr(10,2));
            $('#timeStart').val(sTime.substr(0,4)+"-"+sTime.substr(4,2)+"-"+sTime.substr(6,2)+" "+sTime.substr(8,2)+":"+sTime.substr(10,2));
            load();
        }
    }

})
var map;//地图
var marker;
var lushu;
var timer;
var pointArray = [];
var objArray;
var currentPosition = 0;//暂停之后的位置

var isHaveData;//查询之后是否有数据；
/**
 *按照条件进行查询出对应的人员的轨迹数据
 */
function getPositionTrajectoryList() {
    var timeTemp=$('#timeStart').val();
     var sTime= timeTemp.substr(0,4)+timeTemp.substr(5,2)+timeTemp.substr(8,2)+timeTemp.substr(11,2)+timeTemp.substr(14,2);
    timeTemp=$('#timeEtart').val();
    var eTime= timeTemp.substr(0,4)+timeTemp.substr(5,2)+timeTemp.substr(8,2)+timeTemp.substr(11,2)+timeTemp.substr(14,2);
    pointArray=[];
    isHaveData=false;
    $("#run").attr('disabled', true);
    $.ajax({
        url: "/map/getPositionTrajectoryList",
        dataType: "json",
        type: "post",
        async: false,
        data: {
            "sTime": sTime,
            "eTime": eTime,
            "phoneNum":$("#phoneNum").val()
        },
        success: function (result) {
            var data = result.data;
            //console.log(data,length)
            if(data.length>0){
                isHaveData=true;
                $("#run").attr('disabled', false);
            }
            objArray = data;
            $.each(data, function (index, obj) {
                var point = new BMap.Point(obj.lng, obj.lat);
                pointArray.push(point)

            })
            //坐标转换，未处理
            //var convertor = new BMap.Convertor();
            //convertor.translate(pointArray, 1, 5, translateCallback)
        }
    })
}

/**
 *设计轨迹回放看板
 */
function setTrajectoryInfo(num) {
    $.each(objArray, function (index, obj) {
        if (index == num) {
            var datetime = obj.time.substr(0, 4) + "-" + obj.time.substr(4, 2) + "-" + obj.time.substr(6, 2) + " " + obj.time.substr(8, 2) + ":" + obj.time.substr(10, 2)
            var time = parseInt(obj.lastTime) - parseInt(obj.time)
            var html = "";
            if (index == 0) {
                html = "<div class=\"open-text\">位置：&nbsp;<img src='/images/icon/qidian.png'>&nbsp;(" + obj.lng + "," + obj.lat + ")</div>";
            } else {
                html = "<div class=\"open-text\">位置：&nbsp;<img src='/images/icon/tujing.png'><span style='color: #e09116;font-weight: bold'>" + num + "</span>&nbsp;(" + obj.lng + "," + obj.lat + ")</div><div class=\"open-text\">停留时间：" + time + "(分)</div>";
            }
            $("#showTitle").append("<a id='mark'+num><div class=\"row itemBorder\">\n" +
                "<div class=\"open-text\">时间：" + datetime + "</div>" + html + "</div></a> "
            )
        }
    })
    $("#showTitle")[0].scrollTop = $("#showTitle")[0].scrollHeight

}

/**初始化加载**/
function load() {
    map = new BMap.Map("container");//加载地图

    getPositionTrajectoryList();//按照条件进行查询出对应的人员的轨迹数据

    if(isHaveData) {
        var v = map.getViewport(pointArray);//通过坐标数据得到中心点
        map.centerAndZoom(v.center, v.zoom);//
        map.enableScrollWheelZoom();
        map.disableDoubleClickZoom();

        map.setViewport(pointArray);
        marker = new BMap.Marker(pointArray[0], {
            icon: new BMap.Icon("/images/icon/ren.png", new BMap.Size(32, 32))
        });
        var label = new BMap.Label($("#phoneNum").val(), {offset: new BMap.Size(0, -30)});
        label.setStyle({
            border: "1px solid rgb(204, 204, 204)",
            color: "rgb(0, 0, 0)",
            borderRadius: "10px",
            padding: "5px",
            maxWidth:"150px",
            background: "rgb(255, 255, 255)",
        });
        marker.setLabel(label);
        map.addOverlay(marker);
        var iNum = 0;
        BMapLib.LuShu.prototype._move = function (initPos, targetPos, effect) {
            /**添加起点和途经点**********************/
            var startMarker;
            //途经点大于1的时候开发暂停
            if (iNum > 1) {
                $("#pause").attr('disabled', false);
            }
            //添加起点
            if (iNum == 0) {
                startMarker = new BMap.Marker(initPos, {
                    icon: new BMap.Icon("/images/icon/qidian.png", new BMap.Size(32, 32))
                });
                setTrajectoryInfo(iNum)
            }
            iNum++;
            setTrajectoryInfo(iNum)
            map.addOverlay(startMarker);
            //移除地图上途经
            //
            // var viaMarker = new BMap.Marker(targetPos, {
            //         icon: new BMap.Icon("images/icon/tujing.png", new BMap.Size(32, 32))
            //     });
            // var viaLabel = new BMap.Label(iNum, {
            //     offset: new BMap.Size(15, -9)
            //     })
            //     viaLabel.setContent("<span style='padding:  1px 2px;  border-radius: 50%   -moz-border-radius: 50%;-webkit-border-radius: 50%;background-color: #dd880c'>" + iNum + "</span>")
            //     viaLabel.setStyle({
            //         background: 'none', color: '#fff', border: 'none'//只要对label样式进行设置就可达到在标注图标上显示数字的效果
            //     })
            // viaMarker.setLabel(viaLabel);
            // map.addOverlay(viaMarker);

            /**添加途经点**********************/

            var pointsArr = [initPos, targetPos];  //点数组
            var me = this,
                //当前的帧数
                currentCount = 0,
                //步长，米/秒
                timer = 10,
                step = this._opts.speed / (1000 / timer),
                //初始坐标
                init_pos = this._projection.lngLatToPoint(initPos),
                //获取结束点的(x,y)坐标
                target_pos = this._projection.lngLatToPoint(targetPos),
                //总的步长
                count = Math.round(me._getDistance(init_pos, target_pos) / step);
            //显示折线
            this._map.addOverlay(new BMap.Polyline(pointsArr, {
                strokeColor: "#111",
                strokeWeight: 5,
                strokeOpacity: 0.5
            })); // 画线
            //如果小于1直接移动到下一点
            if (count < 1) {
                me._moveNext(++me.i);
                return;
            }
            me._intervalFlag = setInterval(function () {
                //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
                if (currentCount >= count) {
                    clearInterval(me._intervalFlag);
                    //移动的点已经超过总的长度
                    if (me.i > me._path.length) {
                        return;
                    }
                    //运行下一个点
                    me._moveNext(++me.i);
                } else {
                    currentCount++;
                    var x = effect(init_pos.x, target_pos.x, currentCount, count),
                        y = effect(init_pos.y, target_pos.y, currentCount, count),
                        pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
                    //设置marker
                    if (currentCount == 1) {
                        var proPos = null;
                        if (me.i - 1 >= 0) {
                            proPos = me._path[me.i - 1];
                        }
                        if (me._opts.enableRotation == true) {
                            me.setRotation(proPos, initPos, targetPos);
                        }
                        if (me._opts.autoView) {
                            if (!me._map.getBounds().containsPoint(pos)) {
                                me._map.setCenter(pos);
                            }
                        }
                    }
                    currentPosition = pos;//实时的位置
                    //正在移动
                    me._marker.setPosition(pos);
                    //设置自定义overlay的位置
                    me._setInfoWin(pos);
                }
            }, timer);
        }
        //添加路书的移动的图标
        lushu = new BMapLib.LuShu(map, pointArray, {
            defaultContent: $("#phoneNum").val(),//"从天安门到百度大厦"
            autoView: true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
            // icon: new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52, 26), {anchor: new BMap.Size(27, 13)}),
            icon: new BMap.Icon("/images/icon/ren.png", new BMap.Size(32, 32), {imageOffset: new BMap.Size(0, 0)}),
            speed: 250,
            enableRotation: false,//是否设置marker随着道路的走向进行旋转
            landmarkPois: [
                {lng: 116.306954, lat: 40.05718, html: '加油站', pauseTime: 2}
            ]
        });
    }
}

//改变
$("#forward").click(function () {
    if ($("#spanForward").text() == "快进") {
        lushu._opts.speed = lushu._opts.speed * 2;//改变路书播放速度
        $("#spanForward").text("快进x2")
    }
    else if ($("#spanForward").text() == "快进x2") {
        lushu._opts.speed = lushu._opts.speed * 4;//改变路书播放速度
        $("#spanForward").text("快进x4")
    }
    else if ($("#spanForward").text() == "快进x4") {
        lushu._opts.speed = 250;//改变路书播放速度
        $("#spanForward").text("快进")
    }

});
$("#run").click(function () {
    marker.enableMassClear(); //设置后可以隐藏改点的覆盖物
    marker.hide();
    lushu.start();
})
$("#pause").click(function () {
    lushu.pause();
})


